//
//  LRHomeStatusVM.swift
//  WeiboX
//
//  Created by admin on 05/12/2016.
//  Copyright © 2016 iOS_Objective-C. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage

class LRHomeStatusVM: NSObject {
	
	var statusList: [LRStatusVM] = [LRStatusVM]()

	func loadData(isUp: Bool, callBack: @escaping (Bool, String) -> ()) {
		
		var maxId: Int64 = 0
		var sinceId: Int64 = 0
		
		if isUp {
			// 上拉加载, 获得最后一个元素对应微博的 id
			maxId = statusList.last?.status?.id ?? 0
			print("----------------\(maxId)")
			
			if maxId > 0 {
				// 去除重复的微博 id 数据
				maxId -= 1
			}
		} else {
			// 下拉加载
			sinceId = statusList.first?.status?.id ?? 0
			print(sinceId)
		}
		
		var message = "没有加载到数据"
		
		LRNetworkManager.sharedManager.requestTimeLineData(maxId: maxId, sinceId: sinceId) { (responseObj, error) in
			if error != nil {
				print(error!)
				print("没有请求到数据")
				callBack(false, message)
				return
			}
			
//			print(responseObj!)

			let dic = responseObj as! [String: Any]
			
			let statusDicArr = dic["statuses"] as! [[String: Any]]
			//			print(statusesDicArr)
			
//			var tmpDataArr = [LRStatus]()
//			for statusesDic in statusesDicArr {
//				let status = LRStatus(dic: statusesDic)
//				tmpDataArr.append(status)
//			}
			let modelArr = NSArray.yy_modelArray(with: LRStatus.self, json: statusDicArr) as! [LRStatus]
			
			
//			if modelArr.count > 0 {
//				message = "加载了 \(modelArr.count) 条数据"
//			}
			
			
			var tmpArr = [LRStatusVM]()
			// 使用 YYModel 完成字典转模型
			let group = DispatchGroup()
			for model in modelArr {
				if model.pic_urls?.count == 1 {
					
					if let picUrl = model.pic_urls?.first?.thumbnail_pic {
						group.enter()
						SDWebImageManager.shared().downloadImage(with: URL(string: picUrl), options: [], progress: nil, completed: { (image, error, _, _, _) in
							print("单张图片下载完成")
							
							group.leave()
						})
					}
				}
				
				if model.retweeted_status?.pic_urls?.count == 1 {
					if let picUrl = model.retweeted_status?.pic_urls?.first?.thumbnail_pic {
						
						group.enter()
						SDWebImageManager.shared().downloadImage(with: URL(string: picUrl), options: [], progress: nil, completed: { (image, error, _, _, _) in
							print("转发的单张图片下载完成")
							
							group.leave()
						})
					}
				}
				
				
				let viewModel = LRStatusVM()
				viewModel.status = model
				tmpArr.append(viewModel)
			}
			
			if isUp {
				self.statusList.append(contentsOf: tmpArr)
			} else {
				self.statusList.insert(contentsOf: tmpArr, at: 0)
			}
			
			if tmpArr.count > 0 {
				message = "加载了 \(tmpArr.count) 条数据"
			}
			
			group.notify(queue: DispatchQueue.main, execute: {
				//  表示单张图片都下载完成以后加载微博数据
				print("所有的单张图片都下载完成了")
				callBack(true, message)
			})
			
		}
	}	
}
